import { Injectable, Inject } from '@nestjs/common';
import type { ILanguageService } from '@wwjCommon/language/language.interface';
import { ValidatorService } from '@wwjCommon/libraries/validator/validator.service';
import { CreateUserDto } from '../../dto/create-user.dto';

/**
 * 用户服务
 * 基于PHP的验证器分组方式，符合NestJS规范
 * 
 * 验证器分组: validate_user
 * 多语言支持: 支持API消息、字典数据、验证器消息
 */
@Injectable()
export class UserService {
  constructor(
    @Inject('ILanguageService') private readonly languageService: ILanguageService,
    private readonly validatorService: ValidatorService,
  ) {}

  /**
   * 创建用户
   * 使用场景化验证: add场景
   */
  async create(createUserDto: CreateUserDto) {
    // 模拟创建用户逻辑
    const user = {
      id: Date.now(),
      ...createUserDto,
      created_at: new Date(),
    };

    // 使用多语言API消息
    const message = await this.languageService.getApiMessage('add_success');
    
    return {
      user,
      message,
    };
  }

  /**
   * 获取用户列表
   * 使用多语言字典数据
   */
  async getList(query: any) {
    // 模拟获取用户列表逻辑
    const users = [
      {
        id: 1,
        username: 'admin',
        real_name: '管理员',
        status: 'on',
        type: 'admin',
      },
      {
        id: 2,
        username: 'user1',
        real_name: '用户1',
        status: 'on',
        type: 'user',
      },
    ];

    // 使用多语言字典数据
    const statusDict = await this.languageService.getDictData('dict_user.status_on');
    const typeDict = await this.languageService.getDictData('dict_user.type_admin');

    return {
      users,
      dict: {
        status: statusDict,
        type: typeDict,
      },
    };
  }

  /**
   * 获取用户详情
   */
  async getDetail(id: string) {
    // 模拟获取用户详情逻辑
    if (id === '1') {
      return {
        id: 1,
        username: 'admin',
        real_name: '管理员',
        status: 'on',
        type: 'admin',
      };
    }
    
    return null;
  }

  /**
   * 验证用户数据
   * 使用框架验证器进行业务验证
   */
  async validateUser(userData: any, scene: string = 'add') {
    const errors: string[] = [];

    // 根据场景获取需要验证的字段
    const sceneFields = this.getSceneFields(scene);
    
    for (const field of sceneFields) {
      const value = userData[field];
      
      // 必填验证
      if (this.isRequired(field, value)) {
        const message = await this.languageService.getValidateMessage(`validate_user.${field}_require`);
        errors.push(message);
      }
      
      // 使用框架验证器进行格式验证
      if (value && typeof value === 'string') {
        if (field.includes('email') && !this.validatorService.isEmail(value)) {
          const message = await this.languageService.getValidateMessage(`validate_user.${field}_format`);
          errors.push(message);
        }
        
        if (field.includes('mobile') && !this.validatorService.isMobilePhoneZh(value)) {
          const message = await this.languageService.getValidateMessage(`validate_user.${field}_format`);
          errors.push(message);
        }
      }
    }

    return {
      isValid: errors.length === 0,
      errors,
    };
  }

  /**
   * 获取场景字段
   */
  private getSceneFields(scene: string): string[] {
    const sceneFields: { [key: string]: string[] } = {
      add: ['username', 'password', 'real_name'],
      edit: ['username', 'real_name'],
    };
    
    return sceneFields[scene] || [];
  }

  /**
   * 必填验证
   */
  private isRequired(field: string, value: any): boolean {
    return value === undefined || value === null || value === '';
  }
}
